package main

import (
	"crud-demo/handlers"
	"crud-demo/models"
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

func main() {
	// 初始化数据库连接
	db, err := models.InitDB("root:root@tcp(localhost:3306)/test")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// 设置路由
	r := mux.NewRouter()

	// 用户相关路由
	r.HandleFunc("/", handlers.IndexHandler).Methods("GET")
	r.HandleFunc("/users", handlers.GetUsersHandler).Methods("GET")
	r.HandleFunc("/users/create", handlers.CreateUserHandler).Methods("GET")
	r.HandleFunc("/users/create", handlers.SaveUserHandler).Methods("POST")
	r.HandleFunc("/users/edit/{id}", handlers.EditUserHandler).Methods("GET")
	r.HandleFunc("/users/edit/{id}", handlers.UpdateUserHandler).Methods("POST")
	r.HandleFunc("/users/delete/{id}", handlers.DeleteUserHandler).Methods("GET")

	// 静态文件服务
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	fmt.Println("Server started on :8080")
	log.Fatal(http.ListenAndServe(":8080", r))
}
